package com.yanqu.road.server.gameplayer.module.userinfo.cmd;


import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.userinfo.UserInfoProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.sync.message.SyncResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.concurrent.CompletableFuture;

@Cmd(code = GameProtocol.S_USER_INFO_DETAIL, desc = "用户详情")

public class UserInfoDetailCmd extends AbstractCommand {

    private static Logger logger = LogManager.getLogger(UserInfoDetailCmd.class.getName());

    private UserInfoProto.UserInfoDetailReqMsg reqMsg;

    private UserInfoProto.UserInfoDetailRespMsg.Builder respMsgBuilder = UserInfoProto.UserInfoDetailRespMsg.newBuilder();

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        this.reqMsg = UserInfoProto.UserInfoDetailReqMsg.parseFrom(packet.getBytes());
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        this.respMsgBuilder.setRet(0);
        long serverId = this.reqMsg.getServerId();
        if (serverId == 0) {
            try {
                serverId = Long.parseLong(String.valueOf(this.reqMsg.getUserId()).substring(0, 8));
            } catch (Exception e) {
                logger.info("userId {} parse to serverId error", this.reqMsg.getUserId());
            }
        }
        if (serverId == 0) {
            this.respMsgBuilder.setRet(GameErrorCode.E_ERROR_PARAMETER);
            player.sendPacket(Protocol.U_USER_INFO_DETAIL, this.respMsgBuilder);
            return;
        }

        if (serverId == GameServer.getInstance().getServerId()) {
            UserMgr.userInfoDetail(this.reqMsg.getUserId(), this.reqMsg.getType(), this.reqMsg.getRelationId(), this.respMsgBuilder);
            player.sendPacket(Protocol.U_USER_INFO_DETAIL, this.respMsgBuilder);
        } else {
            CompletableFuture<SyncResponse> responseFuture = GamePlayerMgr.sendToGameServer(serverId, GameProtocol.S_USER_INFO_DETAIL_SERVICE, player.getUserId(), this.reqMsg.toBuilder(), this.respMsgBuilder);
            responseFuture.thenAccept(syncResponse -> {
                if (syncResponse.getErrorCode() == 0) {
                    player.sendPacket(Protocol.U_USER_INFO_DETAIL, this.respMsgBuilder);
                }
            });
        }

    }

    @Override
    public void sendData(GamePlayer player) {

    }
}
